package org.seven;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created by Administrator on 2016/3/14 0014.
 */
public class Client {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Socket server = new Socket("192.168.100.64",8888);
        ObjectOutputStream oos = new ObjectOutputStream( server.getOutputStream());
        ObjectInputStream ois = new ObjectInputStream( server.getInputStream() );

        System.out.println("请输入用户名");
        Users user = new Users(new Scanner(System.in).next(), InetAddress.getLocalHost(), 9999,"XXXXXXXXXXXXXX");
        oos.writeObject(user);

        List<Users> ul = (ArrayList<Users>)ois.readObject();

        server.close(); // 断开连接

        for (Users u : ul ) {
            System.out.println(u.getName() + "\t\t(/" + u.getIp() + ":" + u.getPort() + ")");
        }
        System.out.println("--------------------------------------");

        System.out.print("请选择：");
        int number = new Scanner(System.in).nextInt();
        Users u = ul.get(number);

        // 新建一个线程，去接收消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DatagramSocket ds =
                            new DatagramSocket(u.getPort());
                    byte[] b = new byte[64];
                    DatagramPacket dp =
                            new DatagramPacket(b,b.length);
                    ds.receive(dp);
                    String str = new String(dp.getData(),0,dp.getLength());
                    System.out.println( str );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();     // 线程启动


        // 获取消息
        byte[] b = (user.getName() + ": " + u.getMessage()).getBytes();
        System.out.println(u.getIp() + "\t" + u.getPort());
        DatagramPacket dp =
                new DatagramPacket(b,b.length, u.getIp(), u.getPort());
        DatagramSocket ds = new DatagramSocket();
        ds.send(dp);    // 发送消息
    }
}
